package org.jeecg.modules.kuawcsJs.entity;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;

public class FtpUtil {

	private static Logger logger = LoggerFactory.getLogger(FtpUtil.class);
	private String username;
	private String password;
	private String ip;
	private int port;
	private String characterSet;
	private FTPClient ftpClient = new FTPClient();

	public FtpUtil(String username, String password, String ip, int port) {
		super();
		this.username = username;
		this.password = password;
		this.ip = ip;
		this.port = port;
	}

	/**
	 * 建立连接
	 * @throws IOException 
	 * @throws SocketException 
	 */
	private void connect() throws SocketException, IOException {
		// 连接
		ftpClient.connect(ip, port);
		int reply = ftpClient.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftpClient.disconnect();
		}
		// 登录
		boolean b = ftpClient.login(username, password);
		logger.debug("-------------ftp登录成功:"+b);
		characterSet = "GBK";
		if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持，如果服务器支持就用UTF-8编码，否则就使用本地编码（GBK）.
			characterSet = "UTF-8";
		}
		ftpClient.setDefaultTimeout(30*1000);
		ftpClient.setConnectTimeout(30*1000);
		ftpClient.setDataTimeout(300*1000);
		ftpClient.setControlEncoding(characterSet);
		ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
		ftpClient.enterLocalPassiveMode();
	}

	/**
	 * 关闭输入输出流
	 * @throws IOException
	 */
	private void close() throws IOException {
		ftpClient.logout();//退出登录
		ftpClient.disconnect();//关闭连接
	}

	/**
	 * 下载文件或目录
	 * @param ftpFileName FTP目录
	 * @param localDir	本地目录
	 */
	public void down(String ftpFileName, String localDir) throws IOException {
		System.out.println("路径"+ftpFileName);
	//	ftpFileName=ftpFilePath;
		boolean b = true;
		ftpFileName = getPath(ftpFileName);
		connect();
		downFileOrDir(ftpFileName, localDir);
		deleteDirOrFile(ftpFileName);
		close();
	}

	/**
	 * 下载文件或目录
	 * @param ftpFileName FTP目录
	 * @param localDir	本地目录
	 * @throws IOException 
	 */
	private void downFileOrDir(String ftpFileName, String localDir) throws IOException {
		File temp = new File(localDir);
		if (isDir(ftpFileName)) {
			if(!temp.exists()){
				temp.mkdirs();
			}
			FTPFile[] names = ftpClient.listFiles();
			for (int i = 0; i < names.length; i++) {
				String name = names[i].getName();
				if(name.equals(".") || name.equals("..")) {
					continue;
				}
				downFileOrDir(name, localDir + File.separator + name);
			}
			ftpClient.changeToParentDirectory();
		} else {
			if (temp.isFile()) {
				temp.delete();
			}
			//检查父目录存不存在，不存在则需要创建
			File localfile = new File(localDir);
			String parentPath = localfile.getParent();
			File parentFile = new File(parentPath);
			if(!parentFile.exists()) {
				parentFile.mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(new File(localDir));
			ftpClient.retrieveFile(new String(ftpFileName.getBytes(characterSet), "iso-8859-1"), fos);
			fos.close();
		}
	}

	public FTPFile[] getListFiles(String ftpFileName) throws IOException {
		FTPFile[] s = null;
		connect();
		if (isDir(ftpFileName)) {
			s = ftpClient.listFiles();
		}
		close();
		return s;
	}
	/**
	 * 判断是否是目录
	 * @param fileName	目录名称
	 * @return
	 * @throws IOException 
	 * @throws UnsupportedEncodingException 
	 */
	public boolean isDir(String fileName) throws IOException {
		// 切换目录，若当前是目录则返回true,否则返回true。
		return ftpClient.changeWorkingDirectory(new String(fileName.getBytes(characterSet),"iso-8859-1"));
	}
	
	public long getSize(String target) throws IOException {
		connect();
		long l = sumSize(target);
		close();
		return l;
	}
	
	private long sumSize(String target) throws IOException {
		if(target.endsWith(".")) {
			return 0;
		}
		long size = 0l;
		FTPFile[] ftpFiles = null;
		if (isDir(target)) {
			ftpFiles= ftpClient.listFiles();
			for (FTPFile ftpFile : ftpFiles) {
				if (ftpFile.isFile()) {
					size += ftpFile.getSize();
				}else if (ftpFile.isDirectory()) {
					size += sumSize(ftpFile.getName());
					ftpClient.changeToParentDirectory();
				}
			}
		}else {
			File file = new File(target);
			if (file.getParent() == null || isDir(file.getParent())) {
				ftpFiles= ftpClient.listFiles();
				for (FTPFile ftpFile : ftpFiles) {
					if (ftpFile.getName().equals(file.getName())) {
						size += ftpFile.getSize();
					}
				}
			}else {
				return size;
			}
		}
		return size;
	}
	
	
	/**
	 * 将路径中的斜杠统一
	 * @param ftpPath
	 */
	private String getPath(String ftpPath){
		char[] chars = ftpPath.toCharArray();
		StringBuffer sbStr = new StringBuffer(256);
		for (int i = 0; i < chars.length; i++) {
			if ('\\' == chars[i]) {
				sbStr.append('/');
			} else {
				sbStr.append(chars[i]);
			}
		}
		return sbStr.toString();
	}
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getCharacterSet() {
		return characterSet;
	}

	public void setCharacterSet(String characterSet) {
		this.characterSet = characterSet;
	}

	public static void main(String[] args) throws IOException {
//		FtpUtil ftp = new FtpUtil("admin","jvcnas", "172.18.53.60", 21);
//		ftp.down("/home/admin/receive","D:/tmp");
		FtpUtil ftp = new FtpUtil("admin","jvcnas", "172.18.53.60", 21);
		ftp.down("/home/admin/receive/anguan_guangpan","D:/tmp");
	}


	//删除文件
	public void deleteDirOrFile(String pathname){

		FTPFile[] files = new FTPFile[0];

		try {
			files = ftpClient.listFiles(pathname);
			System.out.println(files.length);
			for (FTPFile f : files){
				if(f.isDirectory()) {

					System.out.println("文件夹空间"+ftpClient.printWorkingDirectory());

					deleteDirOrFile(pathname+"/"+f.getName() );
					ftpClient.changeWorkingDirectory(pathname);
					String path=new String(f.getName().getBytes("utf-8"),"iso-8859-1");
					boolean b=ftpClient.removeDirectory(path); //删除目录下的所有文件后，该目录变成了空目录，可直接删除
					if (b){
						System.out.println("成功删除了文件夹： " + f.getName());
					}

				}
				else if(f.isFile()) {
					ftpClient.changeWorkingDirectory(pathname);

					String path=new String(f.getName().getBytes("utf-8"),"iso-8859-1");
					boolean b=ftpClient.deleteFile(path);
					System.out.println("文件空间"+ftpClient.printWorkingDirectory());
					if (b){
						System.out.println("成功删除了文件： " + f.getName());
					}

				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}


}